package com.bsg.upm.service;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bsg.upm.check.CheckResult;
import com.bsg.upm.check.LoginCheck;
import com.bsg.upm.constant.OperateDictConstants;
import com.bsg.upm.dto.UserDto;
import com.bsg.upm.dto.UserRoleDto;
import com.bsg.upm.entity.UserEntity;
import com.bsg.upm.entity.UserRoleEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;
import com.bsg.upm.util.EncryptionUtils;

@Service
public class LoginService extends BaseService {

	@Resource
	private UserService userService;

	@Resource
	private UserRoleService userRoleService;

	@Resource
	private LoginCheck loginCheck;

	/**
	 * 登录验证
	 * 
	 * @param paramMap
	 * @return
	 * @throws APIException
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson login(Map<String, Object> paramMap) throws APIException {
		try {
			CheckResult chkRS = loginCheck.checkLogin(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}
			String loginName = (String) paramMap.get("loginName");
			// 密码
			String password = (String) paramMap.get("password");
			// 密码加密
			password = EncryptionUtils.getMD5(password);

			// 根据用户名和密码获取用户信息
			UserEntity user = userDao.getUser(loginName, password);
			saveOperateLog(OperateDictConstants.MODEL_LOGIN, OperateDictConstants.ACTION_LOGIN, user.getUsername(),
					user.getName(), user.getUsername(), systemDao.getCurrentDateTime());
			session.setAttribute("user", user);

			UserDto userDto = userService.buildUserBaseDto(user);
			UserRoleEntity role = user.getUserRole();
			if (role != null) {
				UserRoleDto roleDto = userRoleService.buildRoleBaseDto(role);
				userDto.setRole(roleDto);
			}

			return RespJsonFactory.buildOK(userDto);
		} catch (Exception e) {
			logger.error("账号密码验证异常", e);
			throw new APIException("账号密码验证异常:" + e.getMessage());
		}
	}

	/**
	 * 登录验证
	 * 
	 * @param param
	 * @return
	 * @throws APIException
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson loginSSO(Map<String, Object> param) throws APIException {
		try {
			return RespJsonFactory.build(HttpStatus.SC_FORBIDDEN, "UPMSSO登录验证未开发");
		} catch (Exception e) {
			logger.error("账号密码验证异常", e);
			throw new APIException("账号密码验证异常:" + e.getMessage());
		}
	}

	/**
	 * 登出
	 * 
	 * @param request
	 * @return
	 */
	public void logout(HttpServletRequest request) throws APIException {
		request.getSession().invalidate();
	}

}
